import models
import os
import sys
import xmmsclient
import xmmsqt4
from constants import *
from PyQt4 import QtCore, QtGui
from playlistmodel import PlaylistModel
from playlist_ui import Ui_Form

class Playlist(Ui_Form, QtGui.QWidget):
    def __init__(self, xmms2):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)
        self.xmms2 = xmms2
        self.model = PlaylistModel(xmms2)
        self.label.hide()
        self.lineEdit.hide()
        self.playlistProxy = QtGui.QSortFilterProxyModel()
        self.playlistProxy.setSourceModel(self.model)
        self.playlistProxy.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.playlistProxy.setFilterKeyColumn(0)
        self.treeView.setModel(self.playlistProxy)
        self.treeView.setColumnHidden(PLAYLIST_MODEL_ID, True)
        self.addAction(self.actionRemove)
        self.addAction(self.actionFind)
        self.addAction(self.actionHideFilter)
        self.lineEdit.connect(self.lineEdit,
                              QtCore.SIGNAL("textChanged(QString)"),
                              self.playlistProxy.setFilterFixedString)

    def jumpToSelection(self, QModelIndex):
        position =  self.playlistProxy.mapToSource(QModelIndex).row()
        self.xmms2.playlist_set_next(position)
        self.xmms2.playback_tickle(cb=lambda res: self.xmms2.playback_start)

    
    def clear(self):
        playlistName = self.model.playlistName
        self.xmms2.playlist_clear(playlistName)
        
    def remove(self):
        selectedIndexes = self.treeView.selectionModel().selectedRows()
        selectedIndexes.reverse()
        for index in selectedIndexes:
            modelIndex = self.playlistProxy.mapToSource(index)
            self.xmms2.playlist_remove_entry(modelIndex.row(),
                                             self.model.playlistName)

if __name__ == "__main__":
    xmms2 = xmmsclient.XMMS("playlist")
    try:
        xmms2.connect(os.getenv("XMMSPATH"))
    except IOError, detail:
        print "Could not connect to xmms2!", detail
        exit(1)

    app = QtGui.QApplication(sys.argv)
    xmmsqt4.XMMSConnector(xmms2, app)    
    playlist = Playlist(xmms2)
    playlist.show()
    sys.exit(app.exec_())
    
